
import { login } from '@/api/api.verify'
import { getToken, setToken, removeToken,getUname,setUname,removeUname,getUavatar,setUavatar,removeUavatar } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getUname(),
    avatar: getUavatar()
  }
}
//状态列表
const state = getDefaultState()
//修改vuex 的入口
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}
//全局方法
const actions = {
  // user login 登录方法
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(d=>{
        commit('SET_TOKEN', d.data.token)
        commit('SET_NAME', d.data.realName)
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        setToken(d.data.token)
        setUname(d.data.realName)
        setUavatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif")
        resolve();
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info  获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {//获取当前用户信息 获取角色组 并保存登录状态,返回当前角色信息
        const { data } = response

        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const { name, avatar } = data
        //修改用户登录的信息 调用 commit方法
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout  退出登录
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    removeUname()
    removeUavatar()
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token  清除登录信息 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeUname()
      removeUavatar()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

